// pages/user/bindphone.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 'auth',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },

  bindGetUserInfo: function (e) {
    if (e.detail.errMsg !="getUserInfo:ok"){
      app.alert("获取用户信息时发生错误："+e.detail.errMsg+",请删除小程序再试");
    }else{
      this.data.userInfo = e.detail;
      this.login(this.data.userInfo);
    }
   
    //console.log(this.data);
    //this.setData({ page: 'bindphone' })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ extConfig: app.getExtConfigSync() })
    if (options.page){
      this.setData({ page: options.page})
    }
    this.init();
    
  },
  init:function(){
    var that = this;
    wx.getSetting({
      success: function (res) {
        console.log(res);
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              that.data.userInfo = res;
              console.log(res);
              that.login(res);
            }
          })
        } else if (!res.authSetting['scope.userInfo']) {
          that.setData({ page: 'auth' });
        }
      }
    })
  },
  login: function (postData){
    app.loginByUserInfo(postData, function (res) {
      console.log("loginByUserInfo", res);
      if (res.code != 200) {
        app.alert(res.msg);
      } else {
        var backUrl = wx.getStorageSync("backUrl");

        //console.log("backUrl",backUrl);
        if (backUrl) {
          wx.navigateTo({
            url: backUrl,
          })
        } else {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }

      }
    });
  },

  bindgetphonenumber:function(e){
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    if (e.detail.errMsg!="getPhoneNumber:ok"){
      app.alert(e.detail.errMsg);
    }else{
      var postData = this.data.userInfo;
      postData.bindphone = 1;
      postData.encryptedData = e.detail.encryptedData;
      postData.iv = e.detail.iv;
      console.log("postData",postData);
      this.login(postData);
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.init();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})